import React, { Component } from 'react';
import PropTypes from 'prop-types';

class NumbereIncr extends Component {
  constructor(props) {
    super(props);
    this.state = {
      number: 0,
    };
  }

  componentDidMount() {}
  componentWillReceiveProps(nextPorps) {
    if (nextPorps.value > 0) {
      this.setState(
        {
          number: nextPorps.value,
        },
        () => {
          this.numberGrow();
        },
      );
    }
  }
  numberGrow() {
    var ele = window.document.getElementById(this.props.id);
    if (!this.props.animate) {
      ele.innerHTML = this.state.number.toString();
      return;
    }
    let step = Math.ceil((this.state.number * 10) / (this.props.time * 1000));
    let current = 0;
    let start = 0;
    let t = setInterval(() => {
      start += step;
      if (start > this.state.number) {
        clearInterval(t);
        start = this.state.number;
        t = null;
      }
      if (current === start) {
        return;
      }
      current = start;
      if (this.props.fmt) {
        ele.innerHTML = this.numberWithCommas(current.toString());
      } else {
        ele.innerHTML = current.toString();
      }
    }, 10);
  }

  numberWithCommas(x) {
    var parts = x.toString().split('.');
    parts[0] = parts[0]
      .replace(/\D/g, '')
      .replace(/\B(?=(\d{3})+(?!\d))/g, ',');
    return parts.join('.');
  }

  render() {
    return (
      <span className="cm_number_rolling">
        <span id={this.props.id} style={{ fontSize: this.props.fontSize }}>
          0
        </span>
      </span>
    );
  }
}

/*需要的参数*/
NumbereIncr.propTypes = {
  id: PropTypes.string.isRequired, //容器的唯一ID
  time: PropTypes.number, // 执行时间
  value: PropTypes.number.isRequired, // 显示的值
  fmt: PropTypes.bool, //千分位
  fontSize: PropTypes.string, //字体大小
  animate: PropTypes.bool, //是否开启动画
};

/*参数的默认值*/
NumbereIncr.defaultProps = {
  time: 2,
  fmt: true,
  fontSize: '14px',
  animate: true,
};

export default NumbereIncr;
